import Vue from 'vue';
import Router from 'vue-router';
import Login from './views/Login.vue';
import Home from './views/Home.vue';
import PublicActivities from './views/PublicActivities.vue';
import ActivityDetail from './views/ActivityDetail.vue';
import ActivityManagement from './views/ActivityManagement.vue';

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: { requiresAuth: true },
      children: [
        {
          path: 'public-activities',
          name: 'PublicActivities',
          component: PublicActivities,
          meta: { requiresAuth: true }
        },
        {
          path: 'public-activities/:id',
          name: 'ActivityDetail',
          component: ActivityDetail,
          meta: { requiresAuth: true }
        }
      ]
    },
    {
      path: '/activity-management',
      name: 'ActivityManagement',
      component: ActivityManagement,
      meta: { requiresAuth: true, adminOnly: true }
    }
  ]
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userRole = localStorage.getItem('userRole');
  
  // 检查是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!userRole) {
      // 未登录，重定向到登录页
      next({ path: '/login' });
    } else if (to.meta.adminOnly && userRole !== 'admin') {
      // 非管理员尝试访问管理员页面
      alert('您没有权限访问该页面');
      next({ path: '/' });
    } else {
      // 通过所有验证
      next();
    }
  } else {
    // 不需要认证的页面
    next();
  }
});

export default router;